# 门店管理
class Api::StoresController < Api::BaseController
	before_filter :get_region, except: [:update]
	before_filter :get_store, only: [:update_me, :update_products]
	# 门店列表
	# 
	# Params
	# 	access_token: [String] authenication_token
	#   page: [Integer] 页码
	#   per: [Integer] 每页显示数
	# Return
	# 	status: [String] success
	#   list: [Hash] {{id, name, code, contact, phone, address}...}
	#   total: [Integer] 总数
	# Error
	#   status: [String] failed
	def index
		stores = @region.stores.page(params[:page]).per(params[:per])
		render json: {status: :success, list: stores.map(&:to_hash), total: stores.total_count}
	end

	# 创建门店
	#
	# Params
	# 	access_token: [String] authenication_token
	#   store[name]: [String] 门店名称
	# 	admin[name]: [String] 店长姓名
	# 	admin[mobile]: [String] 店长手机号
	# 	store[address]: [String] 地址
	# Return
	# 	status: [String] success
	# 	msg: [String] 创建成功
	# Error
	#   status: [String] failed
	#   msg: [String] msg_infos
	def create
		raise '门店名称重复，无法添加' if @region.stores.where(name: store_params[:name]).count > 0

		sadmin = User.find_or_initialize_by(mobile: params[:admin][:mobile])

		#raise '用户已经注册，请重新创建' unless sadmin.new_record? 
		
		User.transaction do
			Store.transaction do
				sadmin.name 		= params[:admin][:name]
				sadmin.password = ENV['init_ps']
				sadmin.account 	= @current_user.account
				sadmin.role 		= 'operator'
				sadmin.save!

				@region.stores.create!(store_params.merge(account_id: @account.id, user_id: sadmin.id))

				render json: {status: :success, mesg: '创健成功'}
			end
		end
		

		rescue => e
			render json: {status: :failed, msg: e.message}
	end

  def update
    store = Store.find_by(id: params[:id])
    if store.update(store_params)
      render json: {status: :success, msg: :ok, store: store}
    else
      render json: {msg: store.errors.full_messages.first, status: :failed}
    end
  end

	private

	def get_region
		@region = @account.regions.find(params[:region_id])
		raise 'not found' unless @region

		rescue => e
			render json: {status: :failed, msg: e.message}
	end

	def store_params
		params[:store].permit(:name, :address, :rate)
	end

	def get_store
		@store = @current_user.account.stores.find(params[:id])
		raise 'not found' unless @store
		rescue => e
			render json: {status: :failed, msg: e.message}
	end

end
